package com.application;

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import com.application.utils.Base64Utils;
import com.application.utils.RSAHelper;
import com.widget.ButtonProgressView;
import com.widget.HorizontalProgressView;
import com.widget.ProgressView;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import static com.application.Test.privateKey;
import static com.application.Test.publicKey;

public class MainActivity extends AppCompatActivity {
    private int mProgress = 0;
    private ProgressView mProgressView;
    private ButtonProgressView mProView;
    private Handler mHandler = new Handler();
    private HorizontalProgressView mView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mProgressView = (ProgressView) findViewById(R.id.view_progress);
        mProView = (ButtonProgressView) findViewById(R.id.view_pro);
        mView = (HorizontalProgressView) findViewById(R.id.view_horizontalprogressview);
        mHandler.postDelayed(new ProgressRunnable(), 100);
        mProView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                test();
            }
        });
        mProView.setClickable(false);
    }


    //加密数据
    public void test() {
        String source = new String("12345678");
        try {
            source = URLDecoder.decode(source, "utf-8");
            System.out.println("\r加密前文字：\r\n" + source);
            byte[] data = source.getBytes("UTF-8");
            byte[] encodedData = new byte[0];
            try {
                encodedData = RSAHelper.encryptByPublicKey(data, publicKey);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("加密后文字：\r\n" + new String(Base64Utils.encode(encodedData)));
            byte[] decodedData = RSAHelper.decryptByPrivateKey(encodedData, privateKey);
            String target = new String(decodedData);
            System.out.print("解密后文字: " + target);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class ProgressRunnable implements Runnable {

        @Override
        public void run() {
            mProgress ++;
            mProgressView.setProgress(mProgress);
            mProView.setProgress(mProgress);
            mView.updateProgress(mProgress);
            mHandler.postDelayed(this, 50);
            if(mProgress == 100) {
                mProView.setClickable(true);
                mHandler.removeCallbacksAndMessages(null);
            }
        }
    }
}
